﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using BCCommon;
using BCCommon.Enums;
using BCEntity.WeChatComponent.WeChatMessageRecord;
using Dapper;

namespace BCData.WeChatComponent.WeChatMessageRecord
{
    /// <summary>
    /// 微信消息记录数据处理
    /// </summary>
    public class WeChatMessageRecordData : IWeChatMessageRecordData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY = @"SELECT WeChatMessageRecordId,ToUserName,FromUserName,Content,MessageType,
                                              EventName,EventKey,MessageId,CreateTime,IsReply,Title,Description,Url,
                                              LocationX,LocationY,Scale,LocationPrecision,LocationLabel,MediaId,
                                              ThumbMediaId,Fomat,Recognition,PicUrl,Ticket,Replied 
                                        FROM WechatMessageRecord";
        public WeChatMessageRecordData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        public WeChatMessageRecordEntity Add(WeChatMessageRecordEntity weChatMessageRecordEntity)
        {
            string sql = @"INSERT INTO WechatMessageRecord(ToUserName,FromUserName,Content,MessageType,
                                        EventName,EventKey,MessageId,IsReply,Title,Description,Url,LocationX,LocationY,Scale,
                                        LocationPrecision,LocationLabel,MediaId,ThumbMediaId,Fomat,Recognition,PicUrl,Ticket)
                                VALUES (?ToUserName,?FromUserName,?Content,?MessageType,
                                        ?EventName,?EventKey,?MessageId,?IsReply,?Title,?Description,?Url,?LocationX,?LocationY,?Scale,
                                        ?LocationPrecision,?LocationLabel,?MediaId,?ThumbMediaId,?Fomat,?Recognition,?PicUrl,?Ticket);
                            {0} WHERE WeChatMessageRecordId=LAST_INSERT_ID();";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ToUserName", weChatMessageRecordEntity.ToUserName, DbType.AnsiString, size: 50);
            parameters.Add("?FromUserName", weChatMessageRecordEntity.FromUserName, DbType.AnsiString, size: 50);
            parameters.Add("?Content", weChatMessageRecordEntity.Content, DbType.AnsiString, size: 500);
            parameters.Add("?MessageType", weChatMessageRecordEntity.MessageType.ToString(), DbType.AnsiString);
            parameters.Add("?EventName", weChatMessageRecordEntity.EventName, DbType.AnsiString, size: 20);
            parameters.Add("?EventKey", weChatMessageRecordEntity.EventKey, DbType.AnsiString, size: 50);
            parameters.Add("?MessageId", weChatMessageRecordEntity.MessageId, DbType.Int64, size: 20);
            parameters.Add("?IsReply", weChatMessageRecordEntity.IsReply, DbType.Boolean);
            parameters.Add("?Title", weChatMessageRecordEntity.Title, DbType.AnsiString, size: 100);
            parameters.Add("?Description", weChatMessageRecordEntity.Description, DbType.String);
            parameters.Add("?Url", weChatMessageRecordEntity.Url, DbType.AnsiString, size: 1000);
            parameters.Add("?LocationX", weChatMessageRecordEntity.LocationX, DbType.Double);
            parameters.Add("?LocationY", weChatMessageRecordEntity.LocationY, DbType.Double);
            parameters.Add("?Scale", weChatMessageRecordEntity.Scale, DbType.Int32, size: 11);
            parameters.Add("?LocationPrecision", weChatMessageRecordEntity.LocationPrecision, DbType.Double);
            parameters.Add("?LocationLabel", weChatMessageRecordEntity.LocationLabel, DbType.AnsiString, size: 1000);
            parameters.Add("?MediaId", weChatMessageRecordEntity.MediaId, DbType.AnsiString, size: 100);
            parameters.Add("?ThumbMediaId", weChatMessageRecordEntity.ThumbMediaId, DbType.AnsiString, size: 255);
            parameters.Add("?Fomat", weChatMessageRecordEntity.Fomat, DbType.AnsiString, size: 20);
            parameters.Add("?Recognition", weChatMessageRecordEntity.Recognition, DbType.String);
            parameters.Add("?PicUrl", weChatMessageRecordEntity.PicUrl, DbType.AnsiString, size: 1000);
            parameters.Add("?Ticket", weChatMessageRecordEntity.Ticket, DbType.AnsiString, size: 255);
            return this.databaseContext.Master.QueryEntity<WeChatMessageRecordEntity>(string.Format(sql, QUERY), parameters, databaseContext.Transaction);
        }

        public IEnumerable<WeChatMessageRecordEntity> Get(long? recordId,string fromUserName, string toUserName, WeChatMessageType? weChatMessageType, DateTime? start, DateTime? end, bool? isReplied, string eventName, string eventKey, bool? ascending, out int dataCount, int pageIndex = 1, int pageSize = 10, bool mainMessage = true)
        {
            string sql = @"SELECT A.WeChatMessageRecordId,A.ToUserName,C.Nickname AS ToUserNickName,A.FromUserName,
		                            B.Nickname AS FromUserNickName,A.Content,A.MessageType,
		                            A.EventName,A.EventKey,A.MessageId,A.CreateTime,A.IsReply,A.Title,A.Description,A.Url,
		                            A.LocationX,A.LocationY,A.Scale,A.LocationPrecision,A.LocationLabel,A.MediaId,
		                            A.ThumbMediaId,A.Fomat,A.Recognition,A.PicUrl,A.Ticket,A.Replied,B.Sex AS FromUserSex,
		                            B.Headimgurl AS FromUserHeadimgurl,C.Sex AS ToUserSex,C.Headimgurl AS ToUserHeadimgurl
                            FROM WechatMessageRecord A
		                            LEFT JOIN WeChatUserInfo B
				                            ON A.FromUserName=B.Openid
		                            LEFT JOIN WeChatUserInfo C
				                            ON A.ToUserName=C.Openid";
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (recordId.HasValue)
            {
                wheres.Add("A.MessageId=?MessageId");
                parameters.Add("?MessageId", recordId, DbType.Int64, size: 20);
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(fromUserName))
                {
                    wheres.Add("A.FromUserName=?FromUserName");
                    parameters.Add("?FromUserName", fromUserName, DbType.AnsiString, size: 50);
                }
                if (!string.IsNullOrWhiteSpace(toUserName))
                {
                    wheres.Add("A.ToUserName=?ToUserName");
                    parameters.Add("?ToUserName", toUserName, DbType.AnsiString, size: 50);
                }
                if (weChatMessageType.HasValue)
                {
                    wheres.Add("A.MessageType=?MessageType");
                    parameters.Add("?MessageType", weChatMessageType.Value.ToString(), DbType.AnsiString);
                    if (WeChatMessageType.Event == weChatMessageType.Value)
                    {
                        if (!string.IsNullOrWhiteSpace(eventName))
                        {
                            wheres.Add("A.EventName=?EventName");
                            parameters.Add("?EventName", eventName, DbType.AnsiString, size: 20);
                        }
                        if (!string.IsNullOrWhiteSpace(eventKey))
                        {
                            wheres.Add("A.EventKey=?EventKey");
                            parameters.Add("?EventKey", eventKey, DbType.AnsiString, size: 50);
                        }
                    }
                }
                if (start.HasValue && !end.HasValue)
                {
                    wheres.Add("A.CreateTime>=?Start");
                    parameters.Add("?Start", start.Value, DbType.DateTime);
                }
                else if (!start.HasValue && end.HasValue)
                {
                    wheres.Add("A.CreateTime<=?End");
                    parameters.Add("?End", end.Value, DbType.DateTime);
                }
                else if (start.HasValue && end.HasValue)
                {
                    wheres.Add("A.CreateTime>=?Start AND A.CreateTime<=?End");
                    parameters.Add("?Start", start.Value, DbType.DateTime);
                    parameters.Add("?End", end.Value, DbType.DateTime);
                }
                if (isReplied.HasValue)
                {
                    wheres.Add("A.Replied=?Replied");
                    parameters.Add("?Replied", isReplied, DbType.Boolean);
                }
                if (mainMessage)
                {
                    wheres.Add("A.IsReply=?IsReply");
                    parameters.Add("?IsReply", !mainMessage, DbType.Boolean);
                }
            }
            string newsql = string.Format(@"{0} {1} ORDER BY A.CreateTime {4} LIMIT {2},{3}; 
                               SELECT Count(1) FROM WechatMessageRecord A {1}",
                sql,
                wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                pageSize,
                ascending.HasValue && ascending.Value ? "ASC" : "DESC");

            var result = this.databaseContext.Slave.QueryMultiple<WeChatMessageRecordEntity, int>(newsql, parameters);

            dataCount = result.Item2;

            return result.Item1;
        }

        public WeChatMessageRecordEntity GetEntity(long weChatMessageRecordId)
        {
            string sql = @"{0} WHERE WeChatMessageRecordId=?WeChatMessageRecordId;";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WeChatMessageRecordId", weChatMessageRecordId, DbType.Int64, size: 20);
            return this.databaseContext.Slave.QueryEntity<WeChatMessageRecordEntity>(string.Format(sql, QUERY), parameters);
        }

        public WeChatMessageRecordEntity UpdateRepliedStatus(long weChatMessageRecordId)
        {
            string sql = @"UPDATE WechatMessageRecord SET
                                    Replied=1
                            WHERE WeChatMessageRecordId=?WeChatMessageRecordId;
                        {0} WHERE WeChatMessageRecordId=?WeChatMessageRecordId;";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WeChatMessageRecordId", weChatMessageRecordId, DbType.Int64, size: 20);
            return this.databaseContext.Master.QueryEntity<WeChatMessageRecordEntity>(string.Format(sql, QUERY), parameters, databaseContext.Transaction);
        }
    }
}
